<template>
	<view @tap="reset" class="message-list">
		<uni-load-more :status="status" :contentText="{contentnomore: ' '}" />
		<view @tap.stop.prevent="reset(false)" class="message-item" v-for="item in messageList" :key="item.id" :id="'message-'+item.id">
			<xbc-message-time v-if="item.displayTime" :time="item.displayTime" />
			<template v-else>
				<!--系统、通知类消息-->
				<xbc-message v-if="['system', 'notice'].includes(item.type)" mode="custom">
					<xbc-message-system :message="item" />
				</xbc-message>
				<!--常规消息-->
				<xbc-message v-else :message="item" />
			</template>
		</view>
		<view class="xbc-editor-placeholder" :style="{height: placeholderHeight}"></view>
	</view>
	<xbc-editor @change="editorChange" @send="sendMessage" ref="editorRef" />
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { useEditor } from '@/hooks/useEditor'
import { onLoad, onUnload, onPageScroll, onNavigationBarButtonTap } from '@dcloudio/uni-app'
import XBCIM from 'xbcim'
import IM from '@/common/xbcim'

const state = reactive({
	conversationId: '',
	conversationType: XBCIM.CONVERSATION_TYPE.SINGLE,
	nextMessageId: ''
})
const user = ref<any>({})
const status = ref('more')
const editorRef = ref(null)
const messageList = ref([])
const currentScrollTop = ref(0)
const placeholderHeight = ref('60px')
const conversation = uni.getStorageSync('currentConversation')
const { scrollToBottom } = useEditor()

// 设置标题
function setTitle() {
	uni.setNavigationBarTitle({
		title: conversation?.profile?.name
	})
}

// 消息发送
function sendMessage(message: any){
	messageList.value.push(message)
	scrollToBottom()
}

// 编辑器变化
function editorChange(height : string) {
	placeholderHeight.value = height
}

// 重置状态
function reset(isBottom : Boolean = true) {
	editorRef.value?.reset(isBottom)
}

// 获取用户信息
async function getUserProfile(){
	user.value = await XBCIM.getUserProfile()
}

// 获取列表
async function getList() {
	try {
		const { list, nextMessageId } : any = await XBCIM.getMessageList(state)
		
		// 处理时间
		let newList = []
		list.forEach((item : any, index : number) => {
			const previousMessage = index > 0 ? list[index - 1] : null;
			if (previousMessage && item.createTime - previousMessage.createTime < 300) {
			} else {
				const [dateStr, timeStr] = XBCIM.date.toTimeStr(item.createTime)?.split(' ')
				const [year, month, day] = dateStr.split('-')
				const hourMinute = timeStr.split(':')[0] + ':' + timeStr.split(':')[1]
				newList.push({
					id: new Date().getTime() + '-' + index,
					displayTime: (XBCIM.date.isToday(item.createTime) ? '' : `${year}年${month}月${day}日` + '  ') + hourMinute
				})
			}
			newList.push(item)
		})
		
		// 1. 获取当前第一个元素的ID和位置
		const firstId = messageList.value[0]?.id
		
		// 赋值
		if (state.nextMessageId) {
			messageList.value.unshift(...newList)
			nextTick(() => {
				if (firstId) {
					// 定位当前位置
					const query = uni.createSelectorQuery().in(this)
					query.select('#message-'+firstId).boundingClientRect(({ top })=>{
						uni.pageScrollTo({
							duration: 0,
							scrollTop: top
						})
					}).exec()
				}
			})
		} else {
			messageList.value = newList
			setTimeout(() => {
				scrollToBottom()
			}, 20)
		}
		state.nextMessageId = nextMessageId
		status.value = nextMessageId ? 'more' : 'no-more'
	} catch (error) {
		console.log(error)
	}
}

onPageScroll(({ scrollTop }) => {
	currentScrollTop.value = scrollTop
	if(status.value == 'no-more') return
	if(!scrollTop) getList()
	status.value = scrollTop ? 'more' : 'loading'
})

// 监听会话已读
function listenConversationRead() {
	messageList.value.forEach((item) => {
		item.isRead = 1
	})
}

// 监听消息已读
function listenMessageRead(res: any) {
	const readMessageIds = res.list?.map((item: any) => item.id)
	messageList.value.forEach((item) => {
		if (readMessageIds.includes(item.id)) {
			item.isRead = 1
		}
	})
}

// 监听收到消息
async function listenMessageReceived(msg: any) {
	// @ts-ignore 当前会话时更新消息列表
	if (msg.conversationId == state.conversationId) {
		// 自动翻译
		const { autoTranslate, translateTo, userId } = user.value
		if(userId != msg.senderId && (autoTranslate > 0 && translateTo)){
			const translateMessage = await IM.translateMessage(msg)
			Object.assign(msg, translateMessage)
		}
		
		// 判断当前消息是否已经存在列表
		const index = messageList.value.findIndex(message => message.id == msg?.tempId)
		if(index >= 0){
			messageList.value.splice(index, 1, msg)
		}else{
			messageList.value.push(msg)
		}
		
		// @ts-ignore 上报已读回执：仅设置我收到的消息为已读，否则会导致已读数据不准确
		XBCIM.setMessageRead({ messageList: [msg] })
		setTimeout(() => {
			scrollToBottom()
		}, 20)
	}
}

onLoad((query : any) => {
	state.conversationId = query?.id || ''
	XBCIM.setConversationRead({
		conversationId: state.conversationId,
		conversationType: conversation.type
	})
	setTitle()
	getList()
	getUserProfile()
	
	// 监听
	XBCIM.on(XBCIM.EVENT.CONVERSATION_READ, listenConversationRead)
	XBCIM.on(XBCIM.EVENT.MESSAGE_READ, listenMessageRead)
	XBCIM.on(XBCIM.EVENT.MESSAGE_RECEIVED, listenMessageReceived)
})

onUnload(() => {
	XBCIM.off(XBCIM.EVENT.CONVERSATION_READ, listenConversationRead)
	XBCIM.off(XBCIM.EVENT.MESSAGE_READ, listenMessageRead)
	XBCIM.off(XBCIM.EVENT.MESSAGE_RECEIVED, listenMessageReceived)
})

onNavigationBarButtonTap(() => {
	uni.navigateTo({
		url: '/pages/contact/detail?userId='+conversation?.profile?.userId,
		events: {
			clearMessage() {
				messageList.value = []
			}
		}
	})
})
</script>

<style lang="scss" scoped>
.message-list {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: env(safe-area-inset-bottom);
	padding-bottom: constant(safe-area-inset-bottom);

	.message-item {
		margin-bottom: 20rpx;
	}
}

.xbc-editor-placeholder {
	height: 120rpx;
	transition: height 0.3s ease;
	background-color: #f5f5f5;
}
</style>